<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <TableSearch
        :search="state.search"
        @search="onSearch"
        @listenClick="listenClick"
      />
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @delRow="onTableDelRow"
        @pageChange="onTablePageChange"
        @listenClick="listenClick"
      >
        <template #default="{ slotData, slotColumn }">
          <div v-if="slotColumn.key === 'dizhi'" class="textLabel">
            {{
              slotData.province
                ? slotData.province +
                  slotData.city +
                  slotData.area +
                  slotData.address
                : '-'
            }}
          </div>
        </template>
      </Table>
      <PurveyorDialog
        :dialogVisible="dialogVisible"
        :dialogForm="dialogForm"
        :dialogDetail="dialogDetail"
        @cancel="cancel"
        @submit="submit"
      >
      </PurveyorDialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import { deletePurveyor } from '/@/api/assets/index'
import { dictionaryList } from '/@/api/publicApi'
import { buttonDisplayOrNot } from '../../utils/buttonBoolean'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const PurveyorDialog = defineAsyncComponent(
  () => import('./components/PurveyorDialog.vue')
)
const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = ref({
  width: '25%',
  title: ''
})
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'factoryName', colWidth: '', title: '厂家名称', type: 'text' },
      { key: 'factoryTypeName', colWidth: '', title: '厂家类型', type: 'text' },
      { key: 'linkMan', colWidth: '', title: '联系人', type: 'text' },
      { key: 'linkTel', colWidth: '', title: '电话', type: 'text' },
      { key: 'dizhi', colWidth: '', title: '地址', type: 'slot' },
      { key: 'supplyScope', colWidth: '', title: '供应范围', type: 'text' }
      // { key: 'image', colWidth: '', width: '70', height: '40', title: '图片描述', type: 'image' },
    ],
    columnBtn: [
      {
        name: 'editPurveyor',
        text: '编辑',
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'deviceManufactorEditBtn'
      },
      {
        name: 'delPurveyor',
        text: '删除',
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'deviceManufactorDeleteBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePurveyor/purveyorListByPage',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      // type: 1 // 必传参数，分页的不要传
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入厂家名称/联系人搜索',
        type: 'input'
      },
      {
        label: '厂家类型',
        prop: 'factoryType',
        placeholder: '厂家类型',
        type: 'select',
        options: []
      }
    ],
    btn: [
      {
        text: '新增',
        fun: 'addPurveyor',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'deviceManufactorAddBtn'
      }
    ],
    reset: true //重置按钮
  }
})

const geManufactor = () => {
  dictionaryList({ configType: 'factory_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      state.search.param.forEach((i: any) => {
        if (i.prop == 'factoryType') {
          i.options = res.data
          i.options.unshift({
            configValue: '全部厂家',
            customizeFlag: 0,
            id: '',
            parentId: '0'
          })
        }
      })
    }
  })
}
geManufactor()

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  state.tableData.flash = !state.tableData.flash
}

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}

// 删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
  ElMessage.success(`删除${row.name}成功！`)
  getTableData()
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}
const dialogDetail = ref<any>({})
const addPurveyor = () => {
  dialogDetail.value = {}
  dialogForm.value.title = '添加厂家'
  dialogVisible.value = !dialogVisible.value
}

const editPurveyor = (row: any) => {
  dialogForm.value.title = '编辑厂家'
  dialogDetail.value = row
  dialogVisible.value = !dialogVisible.value
}
const cancel = () => {
  dialogVisible.value = !dialogVisible.value
}
const submit = () => {
  dialogVisible.value = !dialogVisible.value
  getTableData()
}

const delPurveyor = (row: any) => {
  ElMessageBox.confirm('是否删除此供应商厂家?', '删除厂家', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deletePurveyor(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addPurveyor: addPurveyor,
  editPurveyor: editPurveyor,
  delPurveyor: delPurveyor
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/assets/supplier') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss">
.textLabel {
  width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
<style>
.el-button--warning.is-plain {
  --el-button-bg-color: #fdf6ec;
  --el-button-hover-text-color: #e6a23c;
  --el-button-hover-bg-color: #fdf6ec;
}

.el-button--warning.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #e6a23c;
}

.el-button--danger.is-plain {
  --el-button-bg-color: #fef0f0;
  --el-button-hover-text-color: #f56c6c;
  --el-button-hover-bg-color: #fef0f0;
}

.el-button--danger.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #f56c6c;
}
</style>
